package leetcode.One_hundred_to_Two_hundred;

/**
 * 110. 平衡二叉树
 */
public class Test110 {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public boolean isBalanced(TreeNode root) {
        return bfs(root) != -1;
    }

    public int bfs(TreeNode node) {
        if (node == null) {
            return 0;
        }
        int left = bfs(node.left);
        if (left == -1) {
            return -1;
        }
        int right = bfs(node.right);
        if (right == -1 || Math.abs(left - right) > 1) {
            return -1;
        }
        return Math.max(left, right) + 1;
    }
}
